package com.sunday.leaf.old.leaf.snowflake;

import com.sunday.common.core.utils.NetUtils;
import com.sunday.leaf.old.leaf.IDGen;
import com.sunday.leaf.old.leaf.common.Result;
import com.sunday.leaf.old.leaf.common.Status;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.Random;

/**
 * @Description: 分布式ID实现
 * @Author: zsy
 * @Create: 2022/10/24 14:47
 */
@Slf4j
public class SnowflakeIDGenImpl implements IDGen {

    /**
     * twepoch表示什么?
     * 由于时间戳只能用69年，我们的计时又是从1970年开始的，所以这个twepoch表示从项目开始的时间，用生成ID的时间减去twepoch作为时间戳，可以使用更久。
     */
    private final long twepoch;
    private final long workerIdBits = 10L;
    private final long maxWorkerId = ~(-1L << workerIdBits);//最大能够分配的workerId = 1023
    private final long sequenceBits = 12L;
    private final long workerIdShift = sequenceBits;
    private final long timestampLeftShift = sequenceBits + workerIdBits;
    private final long sequenceMask = ~(-1L << sequenceBits);
    // 机器ID
    @Getter
    private long workerId;
    // 同一时间的序列
    private long sequence = 0L;
    private long lastTimestamp = -1L;
    private static final Random RANDOM = new Random();

    private SnowflakeIDGenImpl(String zkAddress, int port) {
        // Thu Nov 04 2010 09:42:54 GMT+0800 (中国标准时间)
        this(zkAddress, port, 1288834974657L);
    }

    private SnowflakeIDGenImpl(String zkAddress, int port, long twepoch) {
        Assert.isTrue(timeGen() > twepoch, "[Snowflake] not support twepoch gt currentTime");
        this.twepoch = twepoch;
        SnowflakeZookeeperHolder holder = SnowflakeZookeeperHolder.of(NetUtils.getLocalAddress().getHostAddress(), String.valueOf(port), zkAddress);
        log.info("[Snowflake] twepoch : {}, ip : {}, port : {}, zkAddress : {}", twepoch, holder.getIp(), holder.getPort(), holder.getAddress());
        Assert.isTrue(holder.init(), "[Snowflake] Id Gen is not init ok");
        workerId = holder.getWorkerId();
        log.info("[Snowflake] start success use zk workerId-{}", workerId);
        Assert.isTrue(workerId >= 0 && workerId <= maxWorkerId, "[Snowflake] workerId must gte 0 and lte 1023");
    }

    @Override
    public synchronized Result get() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            long offset = lastTimestamp - timestamp;
            if (offset <= 5) {
                try {
                    wait(offset << 1);
                    timestamp = timeGen();
                    if (timestamp < lastTimestamp) {
                        return new Result(-1, Status.EXCEPTION);
                    }
                } catch (InterruptedException e) {
                    log.error("[Snowflake] wait interrupted");
                    return new Result(-2, Status.EXCEPTION);
                }
            } else {
                return new Result(-3, Status.EXCEPTION);
            }
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                //seq 为0的时候表示是下一毫秒时间开始对seq做随机
                sequence = RANDOM.nextInt(100);
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            //如果是新的ms开始
            sequence = RANDOM.nextInt(100);
        }
        lastTimestamp = timestamp;
        long id = ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
        return new Result(id, Status.SUCCESS);

    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public long getTimestamp(long id) {
        return (id >> timestampLeftShift) + twepoch;
    }

    public static SnowflakeIDGenImpl of(String zkAddress, int port) {
        return new SnowflakeIDGenImpl(zkAddress, port);
    }

    public static SnowflakeIDGenImpl of(String zkAddress, int port, long twepoch) {
        return new SnowflakeIDGenImpl(zkAddress, port, twepoch);
    }


}
